package com.yunlongn.async.log;

import com.yunlongn.async.action.RetryActionWarp;
import com.yunlongn.async.function.RetryActionAdapter;
import com.yunlongn.async.function.RetryScheduleAction;
import com.yunlongn.async.function.RetryScheduleFail;
import com.yunlongn.async.util.spi.SpiOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 * 执行日志记录
 * @author yunlongn
 */
@SpiOrder(1)
public class LoggerActionWarp implements RetryActionWarp {


    @Override
    public <T> RetryScheduleAction<T> warpAction(String retrySubmitId, RetryScheduleAction<T> action, TimeUnit timeUnit, int... periods) {
        LoggerManager.getLogger().taskFirstSubmit(retrySubmitId, action, periods);
        return new RetryActionAdapter<T>(action) {
            @Override
            public boolean execute(Object param) {
                boolean result = super.execute((T) param);
                if (!Boolean.TRUE.equals(result)) {
                    LoggerManager.getLogger().taskRetrySubmit(retrySubmitId);
                } else {
                    LoggerManager.getLogger().taskSuccess(retrySubmitId);
                }
                return result;
            }
            @Override
            public void onFail() {
                try {
                    action.onFail();
                } finally {
                    LoggerManager.getLogger().taskTailFail(retrySubmitId);
                }
            }

        };
    }


}
